package com.flowerfat.wheellib;

import java.util.TimerTask;

import static com.flowerfat.wheellib.MessageHandler.WHAT_INVALIDATE_LOOP_VIEW;
import static com.flowerfat.wheellib.MessageHandler.WHAT_SMOOTH_SCROLL;

/**
 * Created by janus on 2017/7/6.
 * InertiaTimerTask
 */

final class InertiaTimerTask extends TimerTask {
    float a;
    final float velocityY;
    final LoopView loopView;

    InertiaTimerTask(LoopView loopview, float velocityY) {
        this.loopView = loopview;
        this.velocityY = velocityY;
        this.a = Integer.MAX_VALUE;
    }

    @Override
    public final void run() {
        if (a == Integer.MAX_VALUE) {
            if (Math.abs(velocityY) > 2000.0F) {
                if (velocityY > 0.0F) {
                    a = 2000.0F;
                } else {
                    a = -2000.0F;
                }
            } else {
                a = velocityY;
            }
        }

        if (Math.abs(a) >= 0.0F && Math.abs(a) <= 20.0F) {
            loopView.cancelFuture();
            loopView.handler.sendEmptyMessage(WHAT_SMOOTH_SCROLL);
        } else {
            int i = (int) (a * 10.0F / 1000.0F);
            LoopView loopview = loopView;
            loopview.totalScrollY -= i;
            if (!loopView.isLoop) {
                float itemHeight = loopView.lineSpacingMultiplier * (float) loopView.maxTextHeight;
                if (loopView.totalScrollY <= (int) ((float) (-loopView.initPosition) * itemHeight)) {
                    a = 40.0F;
                    loopView.totalScrollY = (int) ((float) (-loopView.initPosition) * itemHeight);
                } else if (loopView.totalScrollY >= (int) ((float) (loopView.items.size() - 1 - loopView.initPosition) * itemHeight)) {
                    loopView.totalScrollY = (int) ((float) (loopView.items.size() - 1 - loopView.initPosition) * itemHeight);
                    a = -40.0F;
                }
            }

            if (a < 0.0F) {
                a += 20.0F;
            } else {
                a -= 20.0F;
            }

            loopView.handler.sendEmptyMessage(WHAT_INVALIDATE_LOOP_VIEW);
        }
    }
}

